package com.pinyoumei.app.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.bean.AccountBean;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.bean.RegisterBean;
import com.pinyoumei.app.bean.WxBindBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.IntentUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.event.WxLoginEvent;
import com.pinyoumei.app.view.LoadingDailog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import io.realm.Realm;

/**
 * Created by Administrator on 2021-08-06.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-06        Administrator             新增Person类
 * 2021-08-06        Administrator             增加sex属性
 */
public class AccountLoginActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_eye;
    private boolean is_eye = false;
    private EditText et_phone;
    private EditText et_password;
    private Button bt_register;
    protected AppManager appManager = AppManager.getInstance();
    private Gson gson;
    private LoadingDailog loadingDailog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtils.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
        StatusBarUtils.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtils.setStatusBarDarkTheme(this, true)){
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtils.setStatusBarColor(this,0x55000000);
        }
        // 添加activity 到栈
        appManager.addActivity(this);

        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();

        setContentView(R.layout.activity_account_login);
        EventBusUtils.register(this);
        InitWidget();

    }



    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEventMain(WxLoginEvent event) {
        if (!TextUtils.isEmpty(event.openid)) {

            WX_BING(event.openid,event.user_nick_name,event.user_head_img);
            EventBusUtils.removeStickyEvent(WxLoginEvent.class);
        }

    }




    private void InitWidget() {

        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);


        ImageView iv_wechat_login = findViewById(R.id.iv_wechat_login);
        iv_wechat_login.setOnClickListener(this);

        TextView tv_rule = findViewById(R.id.tv_rule);
        tv_rule.setOnClickListener(this);
        tv_rule.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线


        TextView tv_forget = findViewById(R.id.tv_forget);
        tv_forget.setOnClickListener(this);

        bt_register = findViewById(R.id.bt_register);
        bt_register.setOnClickListener(this);

        RelativeLayout rl_eye = findViewById(R.id.rl_eye);
        rl_eye.setOnClickListener(this);

        iv_eye = findViewById(R.id.iv_eye);

        et_phone = findViewById(R.id.et_phone);
        et_password = findViewById(R.id.et_password);

        TextChange textChange = new TextChange();
        et_phone.addTextChangedListener(textChange);
        et_password.addTextChangedListener(textChange);
    }


    //EditText的监听器
    class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_phone.length() > 0 &&
                et_password.length() > 0) {
                bt_register.setBackground(ContextCompat.getDrawable(AccountLoginActivity.this, R.drawable.shanpe_green_5dp));

            } else {
                bt_register.setBackground(ContextCompat.getDrawable(AccountLoginActivity.this, R.drawable.shanpe_gray_green_5dp));


            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_wechat_login:

                IntentUtils.loginWeixin(AccountLoginActivity.this,"wxfcdbc78aac617cee");


                break;

            case R.id.tv_rule:
                Intent intent = new Intent(AccountLoginActivity.this, WebViewActivity.class);
                intent.putExtra("order_title", "");
                intent.putExtra("url",Constants.MAIN_URL + "h5/protocol");
                startActivity(intent);
                break;


            case R.id.tv_forget:
                startActivity(new Intent(AccountLoginActivity.this, ForgetPassWordActivity.class));

                break;

            case R.id.rl_eye:
                if (is_eye) {
                    is_eye = false;
                    iv_eye.setImageResource(R.mipmap.ic_close_eye);
                    //否则隐藏密码
                    et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {

                    is_eye = true;
                    iv_eye.setImageResource(R.mipmap.ic_open_eye);
                    //如果选中，显示密码
                    et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                break;

            case R.id.bt_register:
                String phone = et_phone.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                if(!TextUtils.isEmpty(phone)){
                    String rePhone = phone.replace(" ","");
                    if(rePhone.length() != 11){
                        ToastUtils.showLong("请输入正确的手机号!");
                        return;
                    }
                }
                if (TextUtils.isEmpty(phone)){
                    Toast.makeText(AccountLoginActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else  if (TextUtils.isEmpty(password)){
                    Toast.makeText(AccountLoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                }else {
                        LoginData(phone,password,1);
                }
                break;
            default:
                break;
        }
    }

    private void LoginData(String user_phone,String user_pwd,int app_type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", user_phone);
        map.put("user_pwd", user_pwd);
        map.put("app_type", app_type);

        OkGo.<String>post(Constants.LOGIN_CHECK)
                .params("user_phone", user_phone)
                .params("user_pwd", user_pwd)
                .params("app_type", app_type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        RegisterBean registerBean = gson.fromJson(response.body(), RegisterBean.class);

                        if (registerBean.getCode() >= 0) {

                            //保存登录账号的信息的实体类到本地数据库
                            Realm realm = Realm.getDefaultInstance();
                            AccountBean accountBean = new AccountBean();
                            accountBean.setName(registerBean.getResult().getUser_name());
                            accountBean.setPhone(registerBean.getResult().getUser_phone());
                            accountBean.setPassword(user_pwd);
                            accountBean.setApp_user_id(registerBean.getResult().getUser_id());
                            accountBean.setUser_head_image(registerBean.getResult().getUser_head_img());
                            realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    realm.copyToRealmOrUpdate(accountBean);
                                    //进入主界面
                                    SPUtils.saveAppUserId(AccountLoginActivity.this,registerBean.getResult().getUser_id());

                                    SPUtils.saveUserPhone(AccountLoginActivity.this,registerBean.getResult().getUser_phone());


                                    appManager.killActivity(LoginActivity.class);
                                    startActivity(new Intent(AccountLoginActivity.this,MainUIActivity.class));
                                    finish();
                                }
                            });



                        } else {
                            Toast.makeText(AccountLoginActivity.this, registerBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }











    private void WX_BING(String openid,String user_nick_name,String user_head_img)  {
        Map<String, Object> map = new HashMap<>();
        map.put("open_id", openid);



        OkGo.<String>post(Constants.IS_WX_BING)
                .params("open_id", openid)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        WxBindBean wxBindBean = gson.fromJson(response.body(), WxBindBean.class);

                        if (wxBindBean.getCode() >= 0) {
                            SPUtils.saveAppUserId(AccountLoginActivity.this,wxBindBean.getResult().getUser_id());

                            SPUtils.saveUserPhone(AccountLoginActivity.this,wxBindBean.getResult().getUser_phone());

                            SPUtils.saveUserPhone(AccountLoginActivity.this,wxBindBean.getResult().getUser_phone());

                            startActivity(new Intent(AccountLoginActivity.this,MainUIActivity.class));

                            appManager.killActivity(LoginActivity.class);
                            finish();


                        } else {
                            BandWechat( openid,user_nick_name, user_head_img);
                        }

                    }

                });


    }

    private void BandWechat(String open_id,String user_nick_name,String user_head_img) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(AccountLoginActivity.this));
        map.put("open_id", open_id);
        map.put("user_nick_name", user_nick_name);
        map.put("user_head_img", user_head_img);

        OkGo.<String>post(Constants.SETTING_WECHAT_BAND)
                .params("user_id", SPUtils.getAppUserId(AccountLoginActivity.this))
                .params("open_id", open_id)
                .params("user_nick_name", user_nick_name)
                .params("user_head_img", user_head_img)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();

                        BaseBean settingUserBean = gson.fromJson(response.body(), BaseBean.class);

                        if (settingUserBean.getCode() >= 0) {
                            WX_BING(open_id,user_nick_name,user_head_img);
                            ToastUtils.showShort(settingUserBean.getMsg());
                        } else {
                            ToastUtils.showShort(settingUserBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }
}
